import os
import glob
import asyncio
from concurrent.futures import ThreadPoolExecutor
from PIL import Image

Image.MAX_IMAGE_PIXELS = None  # 取消像素限制

# --- 图像格式转webp ---
def find_all_images(source_dir, formats):
    files = []
    for fmt in formats:
        files.extend(glob.glob(os.path.join(source_dir, '**', fmt), recursive=True))
    return files

def convert_image(filepath):
    filename = os.path.splitext(filepath)[0]
    try:
        image = Image.open(filepath)
        webp_limit = 16383
        if max(image.size) > webp_limit:
            ratio = webp_limit / max(image.size)
            new_size = (int(image.size[0]*ratio), int(image.size[1]*ratio))
            image = image.resize(new_size, Image.LANCZOS)
        webp_path = f"{filename}.webp"
        image.save(webp_path, 'WEBP', quality=80, lossless=False)
        image.close()
        os.remove(filepath)
        print(f"已转换: {os.path.basename(filepath)} -> {os.path.basename(webp_path)}")
    except Exception as e:
        print(f"转换失败 {filepath}: {str(e)}")

async def convert_to_webp_async(source_dir):
    formats = ['*.jpg', '*.jpeg', '*.png', '*.gif', '*.bmp']
    files = find_all_images(source_dir, formats)
    print(f"共找到 {len(files)} 张图片，开始转换...")

    loop = asyncio.get_running_loop()
    with ThreadPoolExecutor() as executor:
        tasks = [
            loop.run_in_executor(executor, convert_image, filepath)
            for filepath in files
        ]
        await asyncio.gather(*tasks)
    print("转换完成！")

def run_webp_convert():
    current_dir = os.getcwd()
    print("开始转换图片（包括子文件夹）...")
    asyncio.run(convert_to_webp_async(current_dir))

# --- 入口 ---
def main():
    run_webp_convert()

if __name__ == "__main__":
    main()
